﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using System.Text;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    public class OfficeItemBuyRegController : Common.AdminBaseController
    {
        //
        // GET: /Admin/OfficeItemBuyReg/ 

        public ActionResult Index()
        {
            string strwhere = "";
            List<Model.ItemPurchase> ItemPurchaseList = GetItemPurchaseListList(strwhere, 1);
            return View(ItemPurchaseList);
        }

        public string GetTable(List<Model.ItemPurchaseEntry> ItemPurchaseEntryList, ref int z)
        {
            StringBuilder str = new StringBuilder();
            foreach (Model.ItemPurchaseEntry model in ItemPurchaseEntryList)
            {
                z++;
                str.Append("<tr id='" + z + "'>");
                str.Append(" <td align='center' class='tdClass'><a href='#' onclick=delRow('" + z + "')>删除</a></td>");
                str.Append(" <td align='center' class='tdClass'><a href='#' onclick='popDialog(\"" + model.FItemNo + "\")'>" + model.FItemName + "</a><input type='hidden' id='FItemNo' name='FItemNo' value='" + model.FItemNo + "'></td>");
                str.Append(" <td align='center' class='tdClass'><input type='text' id='FQty' name='FQty' onkeyup=\"this.value=this.value.replace(/[^\\d]/g,'')\" onafterpaste=\"this.value=this.value.replace(/[^\\d]/g,'')\" value='" + model.FQty + "'></td>");
                str.Append(" <td align='center' class='tdClass'><input type='text' id='FPrice' name='FPrice' onkeyup=\"clearNoNum(this)\" onafterpaste=\"clearNoNum(this)\" value='" + model.FPrice + "'></td>");
                str.Append(" <td align='center' class='tdClass'><input type='text' id='FPurchaseDate' name='FPurchaseDate' value='" + model.FPurchaseDate.ToString("yyyy-MM-dd") + "'></td></tr>");
            }
            return str.ToString();
        }

        public ActionResult Save(Model.ItemPurchase model)
        {
            List<Model.ItemPurchaseEntry> ItemPurchaseEntryList = new List<Model.ItemPurchaseEntry>();
            try
            {
                model.FNote = Fetch.Post("FNote");
                model.FEntityNo = Common.GlobalConstant.ENTITYNO;

                string jsAlert = "";
                string[] fItemNos = Fetch.Post("FItemNo").Split(',');
                string[] fQtys = Fetch.Post("FQty").Split(',');
                string[] fPrices = Fetch.Post("FPrice").Split(',');
                string[] fPurchaseDates = Fetch.Post("FPurchaseDate").Split(',');
                string itemNoStr = "";
                for (int i = 0; i < fItemNos.Count(); i++)
                {
                    if (itemNoStr != "")
                    {
                        itemNoStr += ",'" + fItemNos[i] + "'";
                    }
                    else
                    {
                        itemNoStr = "'" + fItemNos[i] + "'";
                    }
                    Model.ItemPurchaseEntry ItemPurchaseEntryModel = new Model.ItemPurchaseEntry();
                    ItemPurchaseEntryModel.FItemNo = fItemNos[i];
                    if (fPrices[i] != "")
                    {
                        ItemPurchaseEntryModel.FPrice = decimal.Parse(fPrices[i]);
                    }
                    else
                    {
                        jsAlert = "单价不许为空";
                    }
                    if (fQtys[i] != "")
                    {
                        ItemPurchaseEntryModel.FQty = decimal.Parse(fQtys[i]);
                    }
                    else
                    {
                        jsAlert = "个数不许为空";
                    }

                    if (fPurchaseDates[i] != "")
                    {
                        DateTime dt ;
                        if (DateTime.TryParse(fPurchaseDates[i], out dt))
                        {
                            ItemPurchaseEntryModel.FPurchaseDate = DateTime.Parse(fPurchaseDates[i]);

                        }
                        else
                        {
                            jsAlert = "请输入正确的时间类型。例：2013-01-01";
                            
                        }

                       
                    }
                    else
                    {
                        jsAlert = "操作时间不许为空";
                    }
                    ItemPurchaseEntryModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                    ItemPurchaseEntryModel.FAmount = ItemPurchaseEntryModel.FPrice * ItemPurchaseEntryModel.FQty;
                    ItemPurchaseEntryList.Add(ItemPurchaseEntryModel);
                }

                if (jsAlert == "")
                {

                    if (Fetch.Post("hdtype") == "Edit")
                    {
                        model.FUpdDate = DateTime.Now;
                        model.FUpdEmplNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                        model.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                        model.FItemPurchaseID = decimal.Parse(Fetch.Post("hdfItemPurchaseID"));
                        BLL.ItemPurchaseEntry ItemPurchaseEntryBLL = new BLL.ItemPurchaseEntry();
                        List<Model.ItemPurchaseEntry> ItemPurchaseEntryOldList = ItemPurchaseEntryBLL.GetModelList("FItemPurchaseID='" + Fetch.Post("hdfItemPurchaseID") + "'");

                        BLL.Item ItemBLL = new BLL.Item();
                        List<Model.Item> ItemList = ItemBLL.GetListAll("");
                        List<Model.Item> NewItemList = new List<Model.Item>();
                        foreach (Model.Item item in ItemList)
                        {
                            List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryOldList where nm.FItemNo == item.FItemNo select nm).ToList();
                            if (SelectPurchaseEntryList.Count > 0)
                            {
                                Model.Item ItemModel = new Model.Item();
                                ItemModel.FItemNo = item.FItemNo;
                                ItemModel.FQty = item.FQty;
                                ItemModel.FAmount = item.FAmount;
                                ItemModel.FPrice = ItemModel.FPrice;
                                for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                                {
                                    ItemModel.FQty = ItemModel.FQty - SelectPurchaseEntryList[i].FQty;
                                    ItemModel.FAmount = ItemModel.FAmount - SelectPurchaseEntryList[i].FAmount;
                                }
                                if (ItemModel.FQty == 0)
                                {
                                    ItemModel.FPrice = 0;
                                }
                                else
                                {
                                    ItemModel.FPrice = ItemModel.FAmount / ItemModel.FQty;
                                }
                                NewItemList.Add(ItemModel);
                            }
                        }

                        List<Model.Item> UpdateItemList = new List<Model.Item>();
                        foreach (Model.Item item in NewItemList)
                        {
                            List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryList where nm.FItemNo == item.FItemNo select nm).ToList();
                            if (SelectPurchaseEntryList.Count > 0)
                            {
                                Model.Item ItemModel = new Model.Item();
                                ItemModel.FItemNo = item.FItemNo;
                                ItemModel.FQty = item.FQty;
                                ItemModel.FAmount = item.FAmount;
                                ItemModel.FPrice = item.FPrice;
                                ItemModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                                for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                                {
                                    ItemModel.FQty = ItemModel.FQty + SelectPurchaseEntryList[i].FQty;
                                    ItemModel.FAmount = ItemModel.FAmount + SelectPurchaseEntryList[i].FAmount;
                                }
                                ItemModel.FPrice = ItemModel.FAmount / ItemModel.FQty;
                                UpdateItemList.Add(ItemModel);
                            }
                            else
                            {
                                Model.Item ItemModel = new Model.Item();
                                ItemModel.FItemNo = item.FItemNo;
                                ItemModel.FQty = item.FQty;
                                ItemModel.FAmount = item.FAmount;
                                ItemModel.FPrice = ItemModel.FPrice;
                                ItemModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                                UpdateItemList.Add(ItemModel);
                            }
                        }

                        BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
                        ItemPurchaseBLL.Update(model, ItemPurchaseEntryList, UpdateItemList);
                        ViewData["fItemPurchaseID"] = Fetch.Post("hdfItemPurchaseID");
                    }
                    else
                    {
                        model.FInsDate = DateTime.Now;
                        model.FInsEmplNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                        model.FInsIP = Common.GenerateUtil.GetClientIPv4Address();
                        BLL.Item ItemBLL = new BLL.Item();
                        List<Model.Item> ItemList = ItemBLL.GetListAll("FItemNo in (" + itemNoStr + ")");
                        List<Model.Item> UpdateItemList = new List<Model.Item>();
                        foreach (Model.Item item in ItemList)
                        {
                            List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryList where nm.FItemNo == item.FItemNo select nm).ToList();
                            if (SelectPurchaseEntryList.Count > 0)
                            {

                                Model.Item ItemModel = new Model.Item();
                                ItemModel.FItemNo = item.FItemNo;
                                ItemModel.FQty = item.FQty;
                                ItemModel.FAmount = item.FAmount;
                                ItemModel.FPrice = item.FPrice;
                                ItemModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                                for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                                {
                                    ItemModel.FQty += SelectPurchaseEntryList[i].FQty;
                                    ItemModel.FAmount += SelectPurchaseEntryList[i].FAmount;
                                }
                                ItemModel.FPrice = ItemModel.FAmount / ItemModel.FQty;
                                UpdateItemList.Add(ItemModel);
                            }
                        }
                        BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
                        ItemPurchaseBLL.Add(model, ItemPurchaseEntryList, UpdateItemList);
                    }
                    ViewData["jsAlert"] = "操作成功";
                }
                else
                {
                    ViewData["jsAlert"] = jsAlert;
                }
            
            }
            catch
            {
                ViewData["jsAlert"] = "操作异常";
            }


            BLL.Item ItemBLLz = new BLL.Item();
            List<Model.Item> ItemListz = ItemBLLz.GetListAll("");
            foreach (Model.Item item in ItemListz)
            {
                List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryList where nm.FItemNo == item.FItemNo select nm).ToList();
                if (SelectPurchaseEntryList.Count > 0)
                {
                    for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                    {
                        SelectPurchaseEntryList[i].FItemName = item.FItemName;
                    }
                }
            }

            ViewData["type"] = Fetch.Post("hdtype");
            int z = 0;
            ViewData["ShowList"] = GetTable(ItemPurchaseEntryList, ref z);
            ViewData["selectIndex"] = z;
            return View("OfficeItemBuyRegEdit", model);
        }

        public string ClickShow(string itemClsNos,string z)
        {
            if (itemClsNos != "")
            {
                string[] nos = itemClsNos.Split(',');
                string noList = "";
                foreach (string no in nos)
                {
                    if (noList != "")
                    {
                        noList += ",'" + no + "'";
                    }
                    else
                    {
                        noList = "'" + no + "'";
                    }
                }
                BLL.Item ItemBLL = new BLL.Item();
                List<Model.Item> ItemList = ItemBLL.GetListAll("FItemNo in (" + noList + ")");
                List<Model.ItemPurchaseEntry> ItemPurchaseEntry = new List<Model.ItemPurchaseEntry>();
                foreach (Model.Item model in ItemList)
                {
                    Model.ItemPurchaseEntry ItemPurchaseEntryModel = new Model.ItemPurchaseEntry();
                    ItemPurchaseEntryModel.FItemNo = model.FItemNo;
                    ItemPurchaseEntryModel.FPurchaseDate = DateTime.Now;
                    ItemPurchaseEntryModel.FQty = 0;
                    ItemPurchaseEntryModel.FItemName = model.FItemName;
                    ItemPurchaseEntryModel.FPrice = model.FPrice;
                    ItemPurchaseEntry.Add(ItemPurchaseEntryModel);
                }
                int zs = int.Parse(z);
                return GetTable(ItemPurchaseEntry, ref zs) + "|" + zs;
            }
            else
            {
                return "";
            }
        }

        public ActionResult OfficeItemBuyRegListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = "";
            List<Model.ItemPurchase> ItemPurchaseList = GetItemPurchaseListList(strwhere, pageIndex);
            return PartialView("OfficeItemBuyRegListPartial", ItemPurchaseList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.ItemPurchase> GetItemPurchaseListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("v_ItemPurchase", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FItemPurchaseID", 0, out total);
            List<ElingOA6_Admin_DSJCJ.Model.ItemPurchase> itemPurchaseList = ItemPurchaseBLL.DataTableToList(ds.Tables[0]);
            List<Model.ItemPurchase> itemPurchaseAllList = new List<Model.ItemPurchase>();

            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                itemPurchaseAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (itemPurchaseList.Count > i)
                {
                    itemPurchaseAllList[((pageIndex - 1) * pageRowSize) + i] = itemPurchaseList[i];
                }
            }

            return itemPurchaseAllList;
        }

        public string DelOfficeItemBuyReg(string FItemPurchaseID)
        {
            try
            {
                BLL.ItemPurchaseEntry ItemPurchaseEntryBLL = new BLL.ItemPurchaseEntry();
                List<Model.ItemPurchaseEntry> ItemPurchaseEntryOldList = ItemPurchaseEntryBLL.GetModelList("FItemPurchaseID='" + FItemPurchaseID + "'");

                BLL.Item ItemBLL = new BLL.Item();
                List<Model.Item> ItemList = ItemBLL.GetListAll("");
                List<Model.Item> NewItemList = new List<Model.Item>();
                foreach (Model.Item item in ItemList)
                {
                    List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryOldList where nm.FItemNo == item.FItemNo select nm).ToList();
                    if (SelectPurchaseEntryList.Count > 0)
                    {
                        Model.Item ItemModel = new Model.Item();
                        ItemModel.FItemNo = item.FItemNo;
                        ItemModel.FQty = item.FQty;
                        ItemModel.FAmount = item.FAmount;
                        ItemModel.FPrice = ItemModel.FPrice;
                        ItemModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                        for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                        {
                            ItemModel.FQty = ItemModel.FQty - SelectPurchaseEntryList[i].FQty;
                            ItemModel.FAmount = ItemModel.FAmount - SelectPurchaseEntryList[i].FAmount;
                        }
                        if (ItemModel.FQty == 0)
                        {
                            ItemModel.FPrice = 0;
                        }
                        else
                        {
                            ItemModel.FPrice = ItemModel.FAmount / ItemModel.FQty;
                        }
                        NewItemList.Add(ItemModel);
                    }
                }

                BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
                ItemPurchaseBLL.Delete(decimal.Parse(FItemPurchaseID), NewItemList);
                return "ok";
            }
            catch
            {
                return "error";
            }
        }

        public string DelOfficeItemBuyRegALL(string FItemPurchaseIDList)
        {
            try
            {
                BLL.ItemPurchaseEntry ItemPurchaseEntryBLL = new BLL.ItemPurchaseEntry();
                List<Model.ItemPurchaseEntry> ItemPurchaseEntryOldList = ItemPurchaseEntryBLL.GetModelList("FItemPurchaseID in (" + FItemPurchaseIDList + ")");

                BLL.Item ItemBLL = new BLL.Item();
                List<Model.Item> ItemList = ItemBLL.GetListAll("");
                List<Model.Item> NewItemList = new List<Model.Item>();
                foreach (Model.Item item in ItemList)
                {
                    List<Model.ItemPurchaseEntry> SelectPurchaseEntryList = (from nm in ItemPurchaseEntryOldList where nm.FItemNo == item.FItemNo select nm).ToList();
                    if (SelectPurchaseEntryList.Count > 0)
                    {
                        Model.Item ItemModel = new Model.Item();
                        ItemModel.FItemNo = item.FItemNo;
                        ItemModel.FQty = item.FQty;
                        ItemModel.FAmount = item.FAmount;
                        ItemModel.FPrice = ItemModel.FPrice;
                        ItemModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                        for (int i = 0; i < SelectPurchaseEntryList.Count; i++)
                        {
                            ItemModel.FQty = ItemModel.FQty - SelectPurchaseEntryList[i].FQty;
                            ItemModel.FAmount = ItemModel.FAmount - SelectPurchaseEntryList[i].FAmount;
                        }
                        if (ItemModel.FQty == 0)
                        {
                            ItemModel.FPrice = 0;
                        }
                        else
                        {
                            ItemModel.FPrice = ItemModel.FAmount / ItemModel.FQty;
                        }
                        NewItemList.Add(ItemModel);
                    }
                }

                BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
                ItemPurchaseBLL.DeleteList(FItemPurchaseIDList, NewItemList);
                return "ok";
            }
            catch
            {
                return "error";
            }
        }

        
        public ActionResult OfficeItemBuyRegEdit(string FItemPurchaseID)
        {
            Model.ItemPurchase itemPurchaseModel = new Model.ItemPurchase();
            int z = 0;
            if (FItemPurchaseID != null && FItemPurchaseID != "")
            {
                BLL.ItemPurchase ItemPurchaseBLL = new BLL.ItemPurchase();
                itemPurchaseModel = ItemPurchaseBLL.GetModel(decimal.Parse(FItemPurchaseID));
                BLL.ItemPurchaseEntry ItemPurchaseEntryBLL = new BLL.ItemPurchaseEntry();
                List<Model.ItemPurchaseEntry> ItemPurchaseEntryList = ItemPurchaseEntryBLL.GetModelList("FItemPurchaseID=" + FItemPurchaseID + "");
                ViewData["ShowList"] = GetTable(ItemPurchaseEntryList,ref z);
                ViewData["selectIndex"] = z;
                ViewData["fItemPurchaseID"] = FItemPurchaseID;
                ViewData["type"] = "Edit";
            }
            else
            {
                itemPurchaseModel.FInsEmplNo = Common.OperateSession.get(Common.GlobalConstant.PARAM_LOGINID);
                ViewData["ShowList"] = "";
                ViewData["selectIndex"] = z;
                ViewData["type"] = "Add";
            }
            return View(itemPurchaseModel);
        }
    }
}
